import hashlib
import json

from flask import render_template, request, session, redirect, jsonify, Response

from blues.login import bp
from blues.login.login_ldap import ldap_login
from model.users import User


# user 普通用户
# auditor 审批员
# ops 运维员
# superadmin 超级管理员


@bp.route('/login', methods=['GET'])
def login_page():
    # 处理Get请求
    return render_template('login.html', error='no')


@bp.route('/api/v1/login', methods=['POST'])
def login_api():
    data = json.loads(request.get_data(as_text=True))  # 获取前端POST传过来的json数据
    # 处理POST请求
    username = data['username'].strip()
    password = data['password'].strip()
    local_account = data['local_account']

    # 判断前端checkbox的勾选状态，判断是否本地用户, 否则ldap用户
    if local_account == "checked":
        print("use local auth")
        login_success = login_local(username, password)
    else:
        print("use ldap auth")
        login_success = login_ldap(username, password)
    # 处理认证信息
    if not login_success:
        res = {"error": "账号密码认证失败"}
        return Response(status=401, mimetype="application/json", response=json.dumps(res))
    res = {'code': 200, 'message': '认证成功'}
    return jsonify(res)


@bp.route('/logout', methods=['GET'])
def logout_api():
    print("logout")
    session.clear()
    return redirect('/login')


def string_md5(string):
    return hashlib.md5(string.encode()).hexdigest()


def login_local(username, password):
    user = User()
    password = string_md5(password)
    result = user.find_by_username(username)
    if len(result) != 1 or result[0]['password'] != password:
        return False
    session['islogin'] = 'true'
    session['username'] = username
    session['role'] = result[0]['role']
    return True


def login_ldap(username, password):
    cn = ldap_login(username, password)
    if not cn:
        return False
    session['islogin'] = 'true'
    session['username'] = cn
    session['role'] = 'admin'  # TODO:通过mysql设定用户权限
    return True


if __name__ == '__main__':
    p1 = string_md5("abcd@1234")
    print(p1)
